// pages/detail/detail.js

const app = getApp();
var WxParse = require('../../wxParse/wxParse.js');
var utils = require("../../utils/util.js");
var noLogin = require("../template/noLogin.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //猜你喜欢的基础url
    baseGoodsImgUrl: 'https://rybc.0791jr.com/data/attachment/item/',
    //图文和评价状态切换
    activeIndex: 0,
    tab: ['图文详情','商品评价'],
    //评价类型进行切换
    commentTypeSelected:0,
    //评论内容
    comments: null, 
    //遮罩层显示状态
    mask:true,
    //承诺保障弹窗
    promiseBox:true,
    //产品参数弹窗
    paramsBox:true,
    //购物车弹窗显示隐藏
    cartBox: true,
    //购买商品数量
    goodsNumber:1,
    //已选规格下标，默认选择第一种规格
    specActive: 0,
    //已选规格价格
    specActivePrice: 0,
    //已选规格库存
    inventory: 0,
    //已选商品限购数量
    limit: null,
    //判断是购物车弹窗还是立即购买
    joinOrBuy: null,
    //是否收藏
    isCollect: null,
    //购物车商品数量
    dot: null,
    item_id: null,
    optionsData: null,
    hasUserInfo: true,   //判断是否获取了用户数据  默认true为获取了
    groupBox: true,  //默认不显示拼团弹窗
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({optionsData: options});
    
  },
  onShow(){
    this.init();
  },

  init(){
    const options = this.data.optionsData;
    this.setData({ JoinGroup: options.pid?true:false})
    wx.showLoading({ title: '加载中...' });
    const userId = app.globalData.userId;
    //获取商品数据
    wx.request({
      url: app.baseURL + 'group&a=item_detail',
      data: {
        item_id: options.item_id,
        a_id: options.a_id,
        user_id: userId
      },
      success: (res) => {
        if (res.data.status == 1 && res.statusCode == 200) {
          let data = res.data;
          //调用wxParse解析html文本
          WxParse.wxParse('goodsinfo', 'html', data.info.info, this, 0);

          const groupList=data.list_pt;
          clearInterval(this.countFun); // //清除定时器避免重复
          this.countFun = setInterval(() => {
            groupList.forEach((item, index) => {
              item.time--;  //时间自减
              item.time < 0 && clearInterval(this.countFun);  // 时间到了清除定时器
              item.starttime = utils.seckill(item.time);
            });
            this.setData({
              groupList: groupList
            });
          }, 1000);

          this.setData({
            data: data,
            info: data.info,
            groupList: data.list_pt,
            isCollect: res.data.collect_status,
            //默认展示全部评价
            comments: data.comment,
            specActive: data.info.did,
            specItemId: data.info.item_id,
          });
          //设置badge
          let badge = wx.getStorageSync('car_num');
          if (badge - 0 > 0) {
            this.setData({
              dot: badge
            })
          }
          wx.hideLoading();
        }
      }
    });
  },

  //图文和评价---选项卡切换
  tabClick(e) {
    this.setData({
      activeIndex: e.currentTarget.id
    });
  },

  //商品评价类型---选项卡切换
  commentTypeClick(e){
    let comments;
    const index = e.currentTarget.dataset.index;
    if (index == 0) { comments = this.data.data.comment;} 
    else if (index == 1) { comments = this.data.data.hpcomment;} 
    else if (index == 2) { comments = this.data.data.zpcomment;} 
    else if (index == 3) { comments = this.data.data.cpcomment;}
    this.setData({
      commentTypeSelected: index,
      comments: comments
    });
  },

  //评论---图片大图预览
  previewImage(e){
    let base = 'https://rybc.0791jr.com/data/attachment/comment/';
    let index = e.currentTarget.dataset.index, //当前图片的下标
      imgs = e.currentTarget.dataset.targetimgs, //当前用户的评论图片
      imgURLs = [];
    //由于后台返回的图片url不是完整的，重新处理一下
    imgs.forEach((item) => { imgURLs.push(base + item.url)});
    //调用大图预览接口
    wx.previewImage({
      current: imgURLs[index], // 当前显示图片的https链接
      urls: imgURLs,  // 需要预览的图片https链接列表
      success: () => {}
    });
  },

  getBanner(){
    wx.request({
      url: app.baseURL + 'Item&a=get_qrcode',
      data: {
        item_id: this.data.item_id,
        path: '/pages/detail/detail?item_id=' + this.data.item_id
      },
      success: (res) => {
        if (res.statusCode == 200) {
          console.log(res)
          wx.previewImage({
            current: ["https://rybc.0791jr.com/data/attachment/qrcode/" + res.data.qrcode][0], // 当前显示图片的https链接
            urls: ["https://rybc.0791jr.com/data/attachment/qrcode/" + res.data.qrcode],  // 需要预览的图片https链接列表
            success: () => { }
          })
        }
      }
    });
  },

  //拨打客服电话
  call(e){
    const tel = e.currentTarget.dataset.tel;
    wx.makePhoneCall({
      phoneNumber: tel,
    })
  },

  //收藏商品
  onOffCollect(e) {
    //收藏
    if (!wx.getStorageSync('userInfo')) {
      noLogin.showNoLogin(this).then(() => {
        //用户授权后更新用户数据
        this.collect(e);
      }).catch(() => {
        this.setData({ hasUserInfo: false }); //判断用户未登录，弹出授权窗口
      });
    } else {
      this.setData({ hasUserInfo: true }); //判断用户已登录，关闭授权窗口
      this.collect(e);
    }

  },


  //收藏
  collect(e){
    const state = this.data.collect_status;
    const userId = app.globalData.userId;
    const itemId = this.data.info.item_id;
    wx.showLoading({ title: '加载中...' });
    wx.request({
      url: app.baseURL + 'Item&a=collect&item_id=' + itemId + '&user_id=' + userId,
      success: (res) => {
        if (res.statusCode == 200) {
          //返回数据成功
          let data = res.data;
          if (data.status == 1 && data.info == '成功取消收藏') {
            wx.showToast({ title: '已取消收藏', icon: 'none' });
            this.setData({ isCollect: false });
          } else if (data.status == 1 && data.info == '收藏成功') {
            wx.showToast({ title: '收藏成功', icon: 'none' });
            this.setData({ isCollect: true });
          }
        }
      }
    }); 
  },

  //显示保障弹窗
  showPromiseBox(){
    this.setData({
      promiseBox: !this.data.promiseBox,
      mask: !this.data.mask
    })
  },

  //显示参数弹窗
  showParamsBox() {
    this.setData({
      paramsBox: !this.data.paramsBox,
      mask: !this.data.mask
    })
  },

  //购买
  purchase(e){
    const status = e.currentTarget.dataset.status,  //判断开团或者拼团
    buy_status = this.data.data.buy_status,  //判断是否已开团
    data={
      gui_id: this.data.specActive, //规格id
      item_id: this.data.specItemId, //商品id
      item_num: 1,  //商品数量
    };
    if (status){
      if (buy_status!=0){
        wx.showModal({
          title: '提示',
          content: '你已参与拼团或拼团还未结束, 立即查看？',
          success: (res)=> {
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/groupStatus/groupStatus?pid=' + buy_status,
              })
            }
          }
        })
      }else{
        if(status){
          data.pid = status,
          data.a_id = this.options.a_id
        }
        wx.navigateTo({
          url: '/pages/placeorder/placeorder?type=4' + '&info=' + JSON.stringify(data)
        })
      }
    }else{
      wx.navigateTo({
        url: '/pages/placeorder/placeorder?type=5' + '&info=' + JSON.stringify(data)
      })
    }
  },

  //用户确认授权
  WeChatUserInfo: function (e) {
    if (e.detail.userInfo) {
      this.setData({ hasUserInfo: true });//发起登录
      noLogin.getUserInfo(this);//用户授权后更新用户数据
    } else {
      wx.showModal({
        title: '温馨提示',
        content: '拒绝微信授权将无法使用部分功能',
        success: res => {
          if (res.confirm) {
            this.setData({ hasUserInfo: true });
          }
        }
      })
    }
  },
  
  //点击遮罩层隐藏弹窗
  hideAllBox() {
    this.setData({
      //遮罩层隐藏
      mask: true,
      //承诺保障弹窗隐藏
      promiseBox: true,
      //产品参数弹窗隐藏
      paramsBox: true,
      //购物车弹窗隐藏
      cartBox: true,
    })
  },
    /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearInterval(this.countFun);   //停止定时器
  },

  move(){},

  // 显示拼团弹窗
  showGroupBox(){
    this.setData({
      groupBox: false
    })
  },
  // 隐藏拼团弹窗
  hideGroupBox(){
    this.setData({
      groupBox: true
    })
  },

  onShareAppMessage: function (res) {
    if (res.from === 'button') {
      // 来自页面内转发按钮
    }
    let data = this.data;
    return {
      title: app.globalData.title,
      path: '/pages/detail/detail?item_id=' + this.data.item_id,
      success: res => {
        console.log("转发成功")
        // 转发成功
      },
      fail: err => {
        // 转发失败
        console.log("转发失败")
      }
    }
  },
})